import 'es6-promise/auto'
//import 'html5-history-api'
//import qs from 'qs'
import axios from 'axios'
import config from '~/config'
import { Message } from 'iview'

// import promise from 'es6-promise'
// promise.polyfill();

// axios 配置
axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

// POST传参序列化
axios.interceptors.request.use((config) => {
    return config
}, (error) => {
    return Promise.reject(error)
})

export default function (options, theConfig) {
    return new Promise((resolve, reject) => {
        options = options || {}
        var baseURl = typeof window === 'undefined' ? config.PortalBaseURL : config.PortalBrowserBaseURL;
        var url = baseURl + theConfig.url
        theConfig.method = theConfig.method.toLocaleLowerCase()

        if (options.query) {
            let query = options.query
            let queryArr = []
            for (let key in query) {
                if (query.hasOwnProperty(key)) {
                    queryArr.push(key + '=' + query[key])
                }
            }
            if (queryArr.length > 0) {
                url += '?' + queryArr.join('&')
            }
        }

        let axiosConfig = {
            method: theConfig.method,
            url: url,
            headers: {}
        }

        if (theConfig.method === 'post' || theConfig.method === 'put') {
            axiosConfig.data = options.body || {}
        }

        let client = options.client
        if (typeof window === 'undefined' && !client) {
            throw new Error(key + ': client不能为空')
        }
        if (client && client.headers) {
            if (client.headers['cookie']) {
                axiosConfig.headers['Cookie'] = client.headers['cookie']
            }
        }
        var startTime = new Date().getTime()

        axios(axiosConfig)
            .then(function (response) {
                if (typeof window === 'undefined') {
                    console.log({
                        url: url,
                        time: (new Date().getTime() - startTime) + 'ms',
                    })
                }
                return resolve(response.data)
            })
            .catch(function (error) {
                if (error.response) {
                    let errorObj = {};
                    if (error.response.status == 400) {
                        errorObj = error.response.data
                        if (!client) { //服务端只提示业务逻辑异常
                            console.log("xsx")
                            Message.error(errorObj.message)
                        }
                    }
                    else {
                        errorObj = { code: error.response.status, message: error.response.statusText }
                    }
                    return reject(errorObj)
                }
                return reject(error)
            })
    })
}